import { last } from 'lodash';

export default (blob, response, name = '下载文件') => {
  if (blob instanceof Blob) {
    // FileReader主要用于将文件内容读入内存
    var reader = new FileReader();
    reader.readAsDataURL(blob);
    // onload当读取操作成功完成时调用
    reader.onload = function (e) {
      var a = document.createElement('a');
      // 获取文件名fileName
      var fileName = last(response.headers?.get?.('content-disposition')?.split?.('=')) || name;
      fileName = decodeURI(fileName);
      fileName = fileName.replace(/"/g, '');
      a.download = fileName;
      a.href = e.target.result;
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
    };
  } else {
    console.error('下载失败：后端返回内容必须为 Blob 类型');
  }
};

export const downLoadByFile = (file) => {
  // 获取文件名fileName
  var fileName = file.name;
  window.open(file.url, '_blank');
};
